/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.yczbj.ycvideoplayer.ability;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSlider;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.yc.kernel.utils.VideoLogUtils;
import com.yc.video.bridge.ControlWrapper;
import com.yc.video.config.ConstantKeys;
import com.yc.video.config.VideoInfoBean;
import com.yc.video.player.SimpleStateListener;
import com.yc.video.player.VideoPlayer;
import com.yc.video.tool.PlayerUtils;
import com.yc.video.ui.view.BasisVideoController;
import com.yc.videocache.cache.PreloadManager;
import com.yc.videocache.cache.ProxyVideoCacheManager;

import org.yczbj.ycvideoplayer.ConstantVideo;
import org.yczbj.ycvideoplayer.ResourceTable;
import org.yczbj.ycvideoplayer.adapter.Tiktok2Adapter;
import org.yczbj.ycvideoplayer.view.TikTokRenderViewFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 模仿抖音短视频，使用VerticalViewPager实现，实现了预加载功能
 *
 * @since 2021-05-11
 */
public class TikTok2Ability extends BaseAbility {
    private static final String KEY_INDEX = "index";
    /**
     * 当前播放位置
     */
    private int mCurPos = -1;
    private List<VideoInfoBean> mVideoList = new ArrayList<>();
    private Tiktok2Adapter mTiktok2Adapter;
    private PreloadManager mPreloadManager;
    private VideoPlayer mVideoPlayer;
    private PageSlider mViewPager;
    private EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());
    private String playUrl;

    /**
     * 启动
     *
     * @param context 上下文
     * @param index 指标
     */
    public static void start(Context context, int index) {
        Intent intent = new Intent();
        intent.setOperation(new Intent.OperationBuilder()
            .withBundleName(context.getBundleName())
            .withAbilityName(TikTok2Ability.class)
            .build());
        intent.setParam(KEY_INDEX, index);
        context.startAbility(intent, 0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mVideoPlayer != null) {
            mVideoPlayer.release();
        }
        mPreloadManager.removeAllPreloadTask();
        // 清除缓存，实际使用可以不需要清除，这里为了方便测试
        ProxyVideoCacheManager.clearAllCache(this);
    }

    @Override
    protected void onActive() {
        super.onActive();
        if (mVideoPlayer != null) {
            mVideoPlayer.resume();
        }
    }

    @Override
    public void onBackPressed() {
        ControlWrapper.defaultValue();
        if (mVideoPlayer == null || !mVideoPlayer.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (mVideoPlayer != null) {
            mVideoPlayer.pause();
        }
    }

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_ability_tik_tok2;
    }

    @Override
    protected void initComponent(Intent intent) {
        super.initComponent(intent);
        mViewPager = (PageSlider) findComponentById(ResourceTable.Id_vvp);
        initView();
    }

    /**
     * 初始化视图
     */
    protected void initView() {
        initViewPager();
        initVideoView();
        mPreloadManager = PreloadManager.getInstance(this);
        Intent extras = getIntent();
        int index = extras.getIntParam(KEY_INDEX, 0);
        mViewPager.setCurrentPage(index);

        runMainThread(new Runnable() {
            @Override
            public void run() {
                startPlay(index);
            }
        });
    }

    /**
     * 切换任务到主线程执行
     *
     * @param runnable 执行的runnable
     */
    public void runMainThread(Runnable runnable) {
        eventHandler.postTask(runnable);
    }

    private void initVideoView() {
        mVideoPlayer = new VideoPlayer(this);
        ComponentContainer decorView = (ComponentContainer) findComponentById(ResourceTable.Id_tok_layout);
        mVideoPlayer.setDecorView(decorView);
        ComponentContainer.LayoutConfig layoutConfig = mVideoPlayer.getLayoutConfig(); // 播放器居中
        layoutConfig.width = ComponentContainer.LayoutConfig.MATCH_PARENT;
        layoutConfig.height = ComponentContainer.LayoutConfig.MATCH_PARENT;
        mVideoPlayer.setLooping(true);

        // 以下只能二选一，看你的需求
        mVideoPlayer.setRenderViewFactory(TikTokRenderViewFactory.create());
        mController = new BasisVideoController(this);
        mVideoPlayer.setController(mController);
        // 监听播放结束
        mVideoPlayer.addOnStateChangeListener(new SimpleStateListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                if (playState == ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING) {
                    runMainThread(new Runnable() {
                        @Override
                        public void run() {
                            playVideo();
                        }
                    });
                }
            }
        });
    }

    /**
     * 重复播放
     */
    private void playVideo() {
        mVideoPlayer.release();
        mController.removeAllControlComponent();
        mController.addDefaultControlComponent("");

        ComponentContainer directionalLayout = (ComponentContainer) mViewPager.getComponentAt(0);
        Component itemView = directionalLayout.getComponentAt(mCurPos);
        Tiktok2Adapter.ViewHolder viewHolder = (Tiktok2Adapter.ViewHolder) itemView.getTag();
        ControlWrapper controlWrapper = mController.getControlWrapper();
        if (controlWrapper != null) {
            controlWrapper.setToggleState(0);
            controlWrapper.setToggleText(viewHolder.mTitle);
            controlWrapper.setToggleControlView(viewHolder.mTikTokView);
        }
        // 重新设置数据
        mVideoPlayer.setUrl(playUrl);

        // 开始播放
        mVideoPlayer.start();
    }

    private void initViewPager() {
        mViewPager = (PageSlider) findComponentById(ResourceTable.Id_vvp);
        mVideoList.addAll(ConstantVideo.getVideoList());
        mViewPager.setPageCacheSize(ConstantVideo.getVideoList().size());
        mTiktok2Adapter = new Tiktok2Adapter(mVideoList);
        mViewPager.setProvider(mTiktok2Adapter);
        mViewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            private int mCurItem;

            /**
             * VerticalViewPager是否反向滑动
             */
            private boolean mIsReverseScroll;

            @Override
            public void onPageSliding(int position, float positionOffset, int positionOffsetPixels) {
                if (position == mCurItem) {
                    return;
                }
                mIsReverseScroll = position < mCurItem;
            }

            @Override
            public void onPageSlideStateChanged(int state) {
                if (state == PageSlider.SLIDING_STATE_DRAGGING) {
                    mCurItem = mViewPager.getCurrentPage();
                }
                if (state == PageSlider.SLIDING_STATE_IDLE) {
                    mPreloadManager.resumePreload(mCurPos, mIsReverseScroll);
                } else {
                    mPreloadManager.pausePreload(mCurPos, mIsReverseScroll);
                }
            }

            @Override
            public void onPageChosen(int position) {
                if (position == mCurPos) {
                    return;
                }
                runMainThread(new Runnable() {
                    @Override
                    public void run() {
                        startPlay(position);
                    }
                });
            }
        });
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        int ordinal = displayOrientation.ordinal();
        if (ordinal == 1) {
            mViewPager.setSlidingPossible(false);
        } else {
            mViewPager.setSlidingPossible(true);
        }
    }

    private void startPlay(int position) {
        if (mCurPos == position) {
            return;
        }
        ComponentContainer directionalLayout = (ComponentContainer) mViewPager.getComponentAt(0);
        Component itemView = directionalLayout.getComponentAt(position);
        if (itemView == null) {
            return;
        }
        Tiktok2Adapter.ViewHolder viewHolder = (Tiktok2Adapter.ViewHolder) itemView.getTag();
        if (viewHolder.mPosition == position) {
            mVideoPlayer.release();
            PlayerUtils.removeViewFormParent(mVideoPlayer);

            VideoInfoBean tiktokBean = mVideoList.get(position);
            playUrl = mPreloadManager.getPlayUrl(tiktokBean.getVideoUrl());
            VideoLogUtils.i("startPlay: " + "position: " + position + "  url: " + playUrl);
            mVideoPlayer.setUrl(playUrl);
            mVideoPlayer.setScreenScaleType(ConstantKeys.PlayerScreenScaleType.SCREEN_SCALE_16_9);

            ControlWrapper controlWrapper = mController.getControlWrapper();
            if (controlWrapper != null) {
                controlWrapper.setToggleState(0);
                controlWrapper.setToggleText(viewHolder.mTitle);
                controlWrapper.setToggleControlView(viewHolder.mTikTokView);
            }
            mController.addControlComponent(viewHolder.mTikTokView, true);
            viewHolder.mPlayerContainer.addComponent(mVideoPlayer, 0);
            mVideoPlayer.start();
            mCurPos = position;
        }
    }
}
